#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <strings.h>
#include <arpa/inet.h>
#include <thread>
#include "InertAddr.hpp"
#include "Log.hpp"
using namespace LogModule;
void Write(int socketfd, InertAddr &addr)
{
    std::string str = "online";
    sendto(socketfd, str.c_str(), sizeof(str), 0, (const sockaddr *)&addr.getaddr(), sizeof(addr.getaddr()));
    while (true)
    {
        std::string message;
        std::cout << "Please Enter# ";
        std::getline(std::cin, message);
        sendto(socketfd, message.c_str(), sizeof(message), 0, (const sockaddr *)&addr.getaddr(), sizeof(addr.getaddr()));
    }
}

void Read(int socketfd)
{
    while (true)
    {
        sockaddr_in sd;
        char buffer[1024];
        socklen_t len = sizeof(sd);
        int n = recvfrom(socketfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&sd, &len);
        buffer[n] = '\0';
        std::cout << buffer << std::endl;
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOG(LogLevel::ERROR) << "Usage: " << argv[0] << " server_op server_port";
    }
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd <= 0)
    {
        LOG(LogLevel::ERROR) << "socket() fail";
    }
    else
    {
        LOG(LogLevel::INFO) << "socket() success _socketfd:" << socketfd;
    }
    InertAddr addr(argv[1], (uint16_t)std::stoi(argv[2]));

    std::thread td_write([&]()
                         {
                             Write(socketfd, addr); // 先发送请求
                         });
    std::thread td_read([&]()
                         { Read(socketfd); });
    td_read.join();
    td_read.join();
    return 0;
}